package life.ks98.community.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import life.ks98.community.dto.AccessTokenDTO;
import life.ks98.community.dto.GiteeUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Kyrie
 * @date 2021/2/10 - 16:54
 */
@Component
public class GiteeProvider {

    /**
     *  获取accessToken
     */
    public String getAccessToken(AccessTokenDTO accessTokenDTO) {
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        // 通过 OKHTTP 发送 post 请求
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?grant_type=authorization_code")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            JSONObject jsonObject = JSON.parseObject(response.body().string());
            /**
             * {"access_token":"7001629e78cf97ad5783edf7bd473d5a",
             * "token_type":"bearer",
             * "expires_in":86400,
             * "refresh_token":"af029823858e2d1056868ccf79b317454017cf56df8ce0df1239da5390c487a7",
             * "scope":"user_info","created_at":1612948198}
             */
            String token = jsonObject.getString("access_token");
            return token;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  获取用户信息
     */
    public GiteeUser getUser(String accessToken) {
        // https://gitee.com/api/v5/user
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token="+accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            GiteeUser giteeUser = JSON.parseObject(string, GiteeUser.class);
            return giteeUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
